<template>
  <div class="custom-el-plus">
    <el-dialog
      v-model="showDialog"
      width="auto"
      destroy-on-close
      :close-on-click-modal="false"
      align-center
      @close="resetData"
      title="事件类型管理"
    >
      <div class="event-dialog">
        <div class="event-table-box">
          <el-table
            :data="state.eventTypeList"
            style="width: 100%"
            class="style-table"
          >
            <el-table-column
              type="index"
              :index="getIndex"
              label="序号"
              width="80"
            />
            <el-table-column
              prop="alarmType"
              label="事件类型"
              width="180"
              show-overflow-tooltip
            >
              <template #default="props">
                <span v-if="!props.row.addFlag" class="evnet-name">{{
                  props.row.alarmType
                }}</span>
                <el-input
                  v-else
                  v-model="props.row.alarmType"
                  maxlength="10"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="threshold" label="报警阈值" width="200">
              <template #default="props">
                <span v-if="!props.row.editFlag">{{
                  props.row.threshold
                }}</span>
                <el-slider v-else v-model="props.row.threshold" />
              </template>
            </el-table-column>
            <el-table-column
              prop="description"
              label="事件描述"
              width="500"
              show-overflow-tooltip
            >
              <template #default="props">
                <span v-if="!props.row.editFlag" class="event-descrition">{{
                  props.row.description
                }}</span>
                <el-input
                  v-else
                  v-model="props.row.description"
                  maxlength="100"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <div class="event-btn-box">
                  <div class="switch-box">
                    <el-switch
                      size="small"
                      v-model="scope.row.startup"
                      :active-value="1"
                      :inactive-value="0"
                      :loading="scope.row.updateLoading"
                      :before-change="beforeUpdate.bind(this, scope.row)"
                    />
                    <span class="statu-label">{{
                      scope.row.startup ? "启用" : "停用"
                    }}</span>
                  </div>
                  <span
                    v-if="!scope.row.editFlag"
                    class="btn-edit"
                    @click="editEventType(scope.row)"
                    >编辑</span
                  >
                  <div v-else>
                    <span class="btn-save" @click="saveEventType(scope.row)"
                      >保存</span
                    >
                    <span class="btn-cancle" @click="cancleSave(scope.row)"
                      >取消</span
                    >
                  </div>
                  <span class="btn-delete" @click="deleteEventType(scope.row)"
                    >删除</span
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="add-btn" @click="addEventType">
          <div class="add-icon">+</div>
          <div class="add-label">新增一行</div>
        </div>
        <div class="page-box">
          <el-pagination
            style="margin-left: auto"
            v-model:current-page="state.currentEventPage"
            :small="small"
            :background="true"
            :page-size="state.pageSize"
            layout="total, prev, pager, next"
            :total="state.eventTotalNum"
            @current-change="handleCurrentEventChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  computed,
  watch,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  reactive,
  defineEmits,
  ref,
  h,
  nextTick,
} from "vue";
const { proxy } = getCurrentInstance();
import { ElMessage, ElMessageBox } from "element-plus";

/* ====================================声明变量================================= */
const props = defineProps({
  eventShow: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits("update:eventShow");
const showDialog = computed({
  get() {
    return props.eventShow;
  },
  set(value) {
    emit("update:eventShow", value);
  },
});
const state = reactive({
  eventTypeList: [],
  eventTotalNum: 0,
  currentEventPage: 1,
  pageSize: 10,
});
/* ====================================事件方法================================= */
const deleteEventType = (row) => {
  ElMessageBox({
    title: "",
    cancelButtonClass: "messagebox-cancel-btn",
    confirmButtonClass: "messagebox-confirm-btn",
    customStyle: {
      backgroundColor: "#0D172F",
      borderRadius: "8px",
    },
    message: h("p", null, [
      h(
        "div",
        { style: "color: #A5ADBA; margin: 2.781vh 0 3.708vh 0.624vw" },
        "确认删除此事件类型?"
      ),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "loading...";
        deleteEventById(row.pkId)
          .then((res) => {
            ElMessage({
              type: "success",
              message: `删除事件成功`,
              duration: 2000,
            });
            done();
            instance.confirmButtonLoading = false;
            getEventList().then((res) => {
              state.eventTypeList = res.list;
              state.eventTotalNum = res.total;
            });
          })
          .catch((err) => {
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    },
  }).then((action) => {});
};
const resetData = () => {
  state.currentEventPage = 1;
  state.eventTypeList = [];
  state.eventTotalNum = 0;
};
const getIndex = (index) => {
  return (state.currentEventPage - 1) * state.pageSize + index < 9
    ? "0" + ((state.currentEventPage - 1) * state.pageSize + (index + 1))
    : (state.currentEventPage - 1) * state.pageSize + (index + 1);
};
const addEventType = () => {
  let data = {
    alarmType: "",
    startup: 1,
    threshold: 50,
    description: "",
    editFlag: true,
    addFlag: true,
  };
  state.eventTypeList.push(data);
};
const editEventType = (row) => {
  row.editFlag = true;
};
const saveEventType = (row) => {
  // 数据校验
  if (row.alarmType == "") {
    ElMessage({
      message: "事件类型不能为空",
      type: "error",
      duration: 3000,
    });
    return;
  }
  if (row.addFlag) {
    addEvent({
      alarmType: row.alarmType,
      threshold: row.threshold,
      description: row.description,
      startup: row.startup,
    })
      .then((res) => {
        ElMessage({
          message: "新增事件类型成功",
          type: "success",
        });
      })
      .finally(() => {
        getEventList().then((res) => {
          state.eventTypeList = res.list;
          state.eventTotalNum = res.total;
        });
      });
  } else {
    updateEvent({
      threshold: row.threshold,
      description: row.description,
      pkId: row.pkId,
    })
      .then((res) => {
        ElMessage({
          message: "事件类型编辑成功",
          type: "success",
        });
      })
      .finally(() => {
        getEventList().then((res) => {
          state.eventTypeList = res.list;
          state.eventTotalNum = res.total;
        });
      });
  }
  row.editFlag = false;
  row.addFlag = false;
};
const cancleSave = (row) => {
  if (row.addFlag) {
    state.eventTypeList.pop();
  }
  row.editFlag = false;
  row.addFlag = false;
};
const handleCurrentEventChange = (val) => {
  getEventList({ pageNum: val }).then((res) => {
    state.eventTypeList = res.list;
    state.eventTotalNum = res.total;
  });
};
const beforeUpdate = (row) => {
  return new Promise((resolve, reject) => {
    if (row.addFlag) {
      return resolve(true);
    } else {
      row.updateLoading = true;
      updateEvent({
        startup: !row.startup ? 1 : 0,
        description: row.description,
        threshold: row.threshold,
        pkId: row.pkId,
      })
        .then((res) => {
          let status = "";
          if (row.startup) {
            status = "停用";
          } else {
            status = "启用";
          }
          ElMessage({
            message: `事件类型${status}成功`,
            type: "success",
          });
          return resolve(true);
        })
        .catch((error) => {
          let status = "";
          if (row.startup) {
            status = "停用";
          } else {
            status = "启用";
          }
          ElMessage({
            message: `事件类型${status}失败`,
            type: "error",
          });
          return reject();
        })
        .finally(() => {
          row.updateLoading = false;
        });
    }
  });
};
/* ====================================接口方法================================= */
const deleteEventById = async (pkId) => {
  const res = await proxy.$http.getFun(`alarm/dict/deleteByPkId/${pkId}`);
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
const getEventList = async (param) => {
  const res = await proxy.$http.postWithBody(
    "alarm/dict/selectAll",
    Object.assign(
      {
        pageNum: state.currentEventPage,
        pageSize: state.pageSize,
      },
      param
    )
  );
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
const updateEvent = async (param) => {
  const res = await proxy.$http.postWithBody("alarm/dict/update", param);
  if (res == 0) {
    throw res;
  }
  return res;
};
const addEvent = async (param) => {
  const res = await proxy.$http.postWithBody("alarm/dict/insert", param);
  if (res == 0) {
    throw res;
  }
  return res;
};
watch(
  () => showDialog.value,
  (newVal, oldVal) => {
    if (newVal) {
      getEventList().then((res) => {
        state.eventTypeList = res.list;
        state.eventTotalNum = res.total;
      });
    }
  }
);
onMounted(() => {});
</script>
<style lang="scss" scoped>
.event-dialog {
  height: pxTvh(730);
  overflow-y: auto;
  & .event-table-box {
    :deep(.el-input) {
      .el-input__inner {
        height: calc(pxTvh(32) - 2px) !important;
        line-height: calc(pxTvh(32) - 2px) !important;
      }
    }

    margin-top: pxTvh(24);
    padding: 0 pxTvh(16) 0 pxTvh(16);
    color: rgba(207, 219, 252, 0.8);
    box-sizing: border-box;
    .evnet-name {
      // max-width: 150px;
      @include overstepForRow();
    }
  }
  & > .add-btn {
    margin: pxTvh(16) 0 0 pxTvh(16);
    --btn-color: #377DFF;
    color: var(--btn-color);
    cursor: pointer;
    @include elasticFN(flex-start, center);
    height: pxTvh(22);
    width: fit-content;
    & > .add-icon {
      width: pxTvw(12);
      height: pxTvw(12);
      border-radius: 50%;
      @include elasticFN(center, center);
      border: 1px solid var(--btn-color);
    }
    & > .add-label {
      height: 100%;
      @include elasticFN(center, center);
      margin-left: pxTvw(10);
    }
  }
  & > .add-btn:hover {
    --btn-color: #4B98FA;
  }
  & > .add-btn:active {
    --btn-color: #154ED1;
  }
  & > .page-box {
    margin: pxTvh(16) pxTvw(16) 0 pxTvw(16);
  }
}
.event-btn-box {
  color: #377dff;
  @include elasticFN(flex-start, center);
  & > .switch-box {
    & > .statu-label {
      color: #d3dfff;
      margin-left: pxTvw(8);
    }
  }
  & > .btn-edit,
  .btn-cancle,
  .btn-save {
    cursor: pointer;
    margin-left: pxTvw(16);
  }
  .btn-delete {
    cursor: pointer;
    color: #e04f3f;
    margin-left: pxTvw(16);
  }
}
</style>